package com.fwj.common.interceptor;

import com.fwj.core.common.common.CommonUtils;
import com.fwj.user.entity.user.UserBaseInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author: fwj
 * @Data: 2022/5/4 1:10
 * @Version 1.0
 * @Description:    拦截WebSocket链接，做Cookie层身份验证
 */

@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketInterceptor.class);

    /**
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        LOGGER.info("开始拦截webSocket握手请求： ");
        //获取Redis中的数据
        HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest();
        String authSession = CommonUtils.getAuthSession(httpServletRequest);
        if (CommonUtils.isEmpty(authSession)){
            LOGGER.info("用户未登录!拦截webSocket请求");
            return false;
        }
        UserBaseInfo userBaseInfo = CommonUtils.getUserBaseInfo(authSession);
        if (CommonUtils.isNotEmpty(userBaseInfo)){
            LOGGER.info("身份验证通过，放行用户： {} ", userBaseInfo.getNumber());
            map.put("userInfo",userBaseInfo);
            return true;
        }
        LOGGER.info("用户未登录!拦截webSocket请求");
        return false;
    }

    /**
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param e
     */
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        LOGGER.info("webSocket握手结束");
    }
}
